package com.webchat.ugc.messaegqueue.consumer.redis;

import com.webchat.common.enums.messagequeue.MessageQueueEnum;
import com.webchat.common.service.messagequeue.consumer.AbstractRedisQueueConsumer;
import com.webchat.common.util.JsonUtil;
import com.webchat.domain.vo.request.mess.ChatMessageRequestVO;
import com.webchat.ugc.messaegqueue.service.PersistentMessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

/**
 * 消息持久化队列消费者
 *
 */
@Component
@Lazy(value = false)
@Slf4j
public class PersistentMessageRedisMQConsumer extends AbstractRedisQueueConsumer<ChatMessageRequestVO> {

    @Autowired
    private PersistentMessageService persistentMessageService;


    public void initBean() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                PersistentMessageRedisMQConsumer.this.schedule();
            }
        }).start();
    }

    @Override
    protected ChatMessageRequestVO convert(String s) {

        return JsonUtil.fromJson(s, ChatMessageRequestVO.class);
    }

    @Override
    protected MessageQueueEnum getMessageQueue() {

        return MessageQueueEnum.QUEUE_PERSISTENT_MESSAGE;
    }

    @Override
    protected void receive(ChatMessageRequestVO data) {
        if (data == null) {
            return;
        }
        boolean result = persistentMessageService.persistent(data);
        // 抛出异常，重新入队
        Assert.isTrue(result, "消息持久化失败");
    }

    @Override
    protected void error(ChatMessageRequestVO data, Exception ex) {

    }
}
